<template>
  <!-- 页面-单据序列管理 -->
  <div 
  :class="{'innerPageTable-box-OneTwo ReceiptSequenceManage-page': !useTableSearchBar}"
  class="run-mod-box innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form
        :model="searchForm"
        ref="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 单据序列编码 -->
        <Form-item prop="receiptSeqCode" :label="$t('module.receiptSequence.receiptSeqCode')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.receiptSeqCode"
            :placeholder="$t('module.receiptSequence.enterReceiptSeqCode')"
            @on-enter="search"
          ></Input>
        </Form-item>

        <!-- 单据序列名称 -->
        <Form-item prop="receiptSeqName" :label="$t('module.receiptSequence.receiptSeqName')">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.receiptSeqName"
            :placeholder="$t('module.receiptSequence.enterReceiptSeqName')"
            @on-enter="search"
          ></Input>
        </Form-item>
        <!-- 状态 -->
        <Form-item prop="isAvailable" :label="$t('common.status')">
          <Select
            v-model="searchForm.isAvailable"
            style="width:100%"
            :placeholder="$t('common.warning.selectStatus')"
            clearable
          >
            <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
              item.vsiValue
            }}</Option>
          </Select>
        </Form-item>
        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="search" />
          <RPButton optType="reset" @click="reset" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="pageTable" :config="pageTableConfig">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="add" />
        <RPButton optType="batch" @click="deleted" />
      </div>
      <Form
        :model="searchForm"
        v-if="useTableSearchBar"
        ref="searchForm"
        slot="table-search-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <!-- 单据序列编码 -->
        <Form-item prop="receiptSeqCode">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.receiptSeqCode"
            :placeholder="$t('module.receiptSequence.enterReceiptSeqCode')"
            clearable
            @on-enter="search"
            @on-blur="search"
            @on-clear="search"
          ></Input>
        </Form-item>

        <!-- 单据序列名称 -->
        <Form-item prop="receiptSeqName">
          <Input
            type="text"
            :maxlength="30"
            v-model.trim="searchForm.receiptSeqName"
            :placeholder="$t('module.receiptSequence.enterReceiptSeqName')"
            clearable
            @on-enter="search"
            @on-blur="search"
            @on-clear="search"
          ></Input>
        </Form-item>
        <!-- 状态 -->
        <Form-item prop="isAvailable">
          <Select
            v-model="searchForm.isAvailable"
            @on-change="search(1)"
            style="width:140px"
            :placeholder="$t('common.warning.selectStatus')"
            clearable
          >
            <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
              item.vsiValue
            }}</Option>
          </Select>
        </Form-item>
      </Form>
    </InnerPageTable>
  </div>
</template>
<script>
import ReceiptSequenceEdit from './ReceiptSequenceEdit.vue'
import ReceiptSequenceRule from './ReceiptSequenceRule.vue'
import { ComTypes, CoreModuleName } from '@/const.js'
import { GetValueSetByCode } from './common.js'
import role from '@lang/modules/role'
import valueSet from '@lang/modules/valueSet'
import receiptSequence from '@lang/modules/receiptSequence'
import userManage from '@lang/modules/userManage'
import tenantManage from '@lang/modules/tenantManage'
import valueSetAPI from '@/api/valueSetAPI.js'
import tenantAPI from '@/api/tenantApi.js'

export default {
  components: {},
  name: 'receipt-sequence-manage',
  locales: {
    'zh-CN': {
      module: {
        receiptSequence: receiptSequence['zh-CN'],
        role: role['zh-CN'],
        valueSet: valueSet['zh-CN'],
        userManage: userManage['zh-CN'],
        tenantManage: tenantManage['zh-CN']
      }
    },
    'en-US': {
      module: {
        receiptSequence: receiptSequence['en-US'],
        role: role['en-US'],
        valueSet: valueSet['en-US'],
        userManage: userManage['en-US'],
        tenantManage: tenantManage['en-US']
      }
    }
  },
  props: {},
  data() {
    const vm = this
    return {
      roleList: [],
      productList: [],
      tenantList: [],
      pageTableConfig: {
        title: this.$t('module.receiptSequence.pageTitle'),
        formDirection: 'column', //default
        action: null,
        resource: null, //default
        customDataProcess: null, //default
        loadDataFn: this.GetReceiptSequencePage,
        columnsFn: this.columns,
        autoFirst: false, //default false
        searchLabelPosition: 'top', //default
        rowClassNameFn: this.rowClassName, // 自定义行样式
        onSelectionChange(_selected) {
          vm.selected = _selected
        }
      },
      searchStatusList: [], //状态
      searchForm: {
        productId: '',
        tenantCode: '',
        receiptSeqCode: '',
        receiptSeqName: '',
        isAvailable: 'ALL'
      }
    }
  },
  created: function() {
    this.init()
    this.initProduct()
    this.searchStatusList = [
      {
        vsiKey: '0',
        vsiValue: this.$t('common.disable')
      },
      {
        vsiKey: '1',
        vsiValue: this.$t('common.enable')
      }
    ]
  },
  mounted: function() {},
  methods: {
    // 自定义行样式
    rowClassName(row) {
      // isShowAsh:1-灰化，1-不灰化
      if (row.isShowAsh == 1) {
        return 'tableDisableStyle'
      }
    },
    init() {
      const { currentPost } = $store.state[CoreModuleName]
      if (!currentPost) return

      // 根据当前岗位查询数据
      this.searchForm.productId = currentPost.productId
      this.searchForm.tenantCode = currentPost.tenantCode

      this.initProduct()
      this.initTenant()
    },
    // 初始化所属产品
    initProduct() {
      valueSetAPI.getValueSetByCode('RC_PRODUCT').then(data => {
        for (const product of data) {
          this.productList[product.vsiKey] = product.vsiValue
        }
        this.search()
      })
    },

    // 初始化所属租户
    initTenant() {
      tenantAPI.queryAllTenantList().then(data => {
        for (const tenant of data) {
          this.tenantList[tenant.tenantCode] = tenant.tenantName
        }
      })
    },
    add() {
      new this.$pageModal(
        ReceiptSequenceEdit,
        {
          props: {
            adminProductId: this.searchForm.productId,
            tenantCode: this.searchForm.tenantCode
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    // getIds() {
    //   this.$refs["pageTable"].resetFields();
    //   let ids = [];
    //   for (let ff of this.selected || []) {
    //     ids.push(ff.id);
    //   }
    //   return ids;
    // },
    getSelectedIds() {
      let list = this.$refs['pageTable'].getSelectioned() || []
      let ids = []
      for (let item of list) {
        ids.push(item.id)
      }
      return ids
    },
    deleted(id) {
      let receiptSeqIds = []
      if (typeof id == 'string') {
        receiptSeqIds = [id]
      } else {
        receiptSeqIds = this.getSelectedIds()
      }
      if (receiptSeqIds.length == 0) {
        this.$message.error(this.$t('common.warning.selctElement'))
        return
      }
      new $confirm(this.$t('module.receiptSequence.confirmToDelete'), this).then(() => {
        $http.post(`${window.RPConfig.setting}/sys/receiptSeq/delete`, receiptSeqIds).then(response => {
          response = response && response.data
          this.$message.success({
            content: this.$t('module.receiptSequence.deleteSuccess'),
            duration: 3
          })

          this.search()
        })
      })
    },
    GetReceiptSequencePage({ responseProcess, param }) {
      return window.$http.post(`${window.RPConfig.setting}/sys/receiptSeq/list/page`, param).then(response => {
        // 状态为有效：禁用复选框，不可删除
        let { records } = response.data
        records = this.$root.$options.filters['selection-disabled'](records)
        responseProcess(response.data)
      })
    },
    columns() {
      const COLUMN_WIDTH = window.RPConfig.COLUMN_WIDTH
      return [
        {
          type: 'selection',
          width: 45,
          // fixed: 'left',
          align: 'center'
        },

        {
          title: this.$t('module.receiptSequence.receiptSeqCode'),
          key: 'receiptSeqCode',
          // sortable: "custom",
          align: 'left',
          // width: 170,
          sortable: true,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.receiptSeqCode
                }
              },
              params.row.receiptSeqCode
            )
          }
        },
        {
          title: this.$t('module.receiptSequence.receiptSeqName'),
          key: 'receiptSeqName',
          // sortable: "custom",
          align: 'left',
          // width: 160,
          sortable: true,
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.receiptSeqName
                }
              },
              params.row.receiptSeqName
            )
          }
        },

        {
          title: this.$t('common.describe'), // module.receiptSequence.receiptSeqDesc 单据序列描述 改为 描述
          key: 'receiptSeqDesc',
          align: 'left',
          render: (h, params) => {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.receiptSeqDesc
                }
              },
              params.row.receiptSeqDesc
            )
          }
        },
        {
          title: this.$t('common.status'),
          key: 'isAvailable',
          align: 'center',
          minWidth: 80,
          maxWidth: 80 + COLUMN_WIDTH.MAX_WIDTH_MORE,

          render: (h, params) => {
            return h(
              'StatusButton',
              {
                // 修改StatusButton内容居中
                style: {
                  "justify-content": "center"
                },

                props: {
                  status: params.row.isAvailable == 1 ? '0' : '1'
                }
              },
              params.row.isAvailable == 1 ? this.$t('common.enable') : this.$t('common.disable')
            )
          }
        },
        {
          title: this.$t('common.operating'),
          fixed: 'right',
          width: 100,
          render: (h, params) => {
            return h('RowTools', {
              props: {
                data: [
                  {
                    type: 'icon',
                    icon: 'md-create',
                    text: this.$t('common.edit'),
                    handle: () => {
                      this.edit(params.row.id, params.row.version)
                    }
                  },
                  {
                    type: 'icon',
                    icon: 'ios-settings',
                    text: this.$t('module.receiptSequence.editCodeRule'),
                    handle: () => {
                      this.editCodeRule(params.row)
                    }
                  },
                  {
                    type: 'icon',
                    icon: 'ios-trash',
                    text: this.$t('common.delete'),
                    hidden: params.row.isAvailable == '1',
                    handle: () => {
                      this.deleted(params.row.id)
                    }
                  }
                ]
              }
            })
          }
        }
      ]
    },
    edit(id, version) {
      new this.$pageModal(
        ReceiptSequenceEdit,
        {
          props: {
            adminProductId: this.searchForm.productId,
            tenantCode: this.searchForm.tenantCode,
            receiptSeqId: id,
            version: version
          }
        },
        data => {
          data && this.search(this.$refs.pageTable.param.pageNum)
        }
      )
    },
    editCodeRule(row) {
      new this.$sidelipPage(
        ReceiptSequenceRule,
        {
          props: {
            obj: {
              receiptSeqId: row.receiptSeqId,
              receiptSeqCode: row.receiptSeqCode,
              receiptSeqName: row.receiptSeqName,
              resetFrequency: row.resetFrequency,
              version: row.version,
              isAvailable: row.isAvailable
            }
          }
        },
        data => {}
      )
    },
    search(page = 1) {
      // this.$refs["pageTable"].load(this.searchForm, page);
      let searchParams = Object.assign({}, this.searchForm)
      if (searchParams.isAvailable == 'ALL') {
        searchParams.isAvailable = null
      }
      this.$refs['pageTable'].load(searchParams, page)
    },
    reset() {
      this.$refs['searchForm'].resetFields()
      this.search()
    }
  }
}
</script>

<style lang="less">
// ok注释的样式
.ReceiptSequenceManage-page {
  .ivu-form-item {
    .ivu-form-item-content {
      width: calc(~'100% - 94px') !important;
    }
  }
}
</style>
